//弹窗
function confirms(content, callback) {
    return new Promise((resolve) => {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'v-modal';
        overlay.style.cssText = 'position: fixed; inset: 0; z-index: 2000; background-color: rgba(0,0,0,0.5);';

        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = 'el-message-box__wrapper';
        dialog.style.cssText = 'position: fixed; inset: 0; z-index: 2001; display: flex; align-items: center; justify-content: center;';
        dialog.innerHTML = `
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title"><span>系统提示</span></div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__message"><p>${content}</p></div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small cancel-btn">
            <span>取消</span>
          </button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary confirm-btn">
            <span>确认</span>
          </button>
        </div>
      </div>
    `;
        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 绑定确认按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => {
            removeDialog(overlay, dialog); // 关闭弹窗
            callback(true); // 调用回调并传入结果（true=确认）
        });
        // 绑定取消按钮事件
        const cancelBtn = dialog.querySelector('.cancel-btn');
        cancelBtn.addEventListener('click', () => {
            resolve(false); // 点击取消返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 绑定遮罩层点击事件
        overlay.addEventListener('click', () => {
            resolve(false); // 点击遮罩返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 统一关闭弹窗函数
        function removeDialog(overlay, dialog) {
            overlay.remove();
            dialog.remove();
        }
    });
}
function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}


//性别
const genderSave = document.getElementById('gender-save');
const genderCancel = document.getElementById('gender-cancel');
const genderEdit = document.getElementById('gender-edit');
const genderInput = document.getElementById('gender-form');
const gender = document.getElementById('gender');

genderEdit.addEventListener('click', function () {
    genderInput.style.display = 'block';
    genderSave.style.display = 'block';
    genderCancel.style.display = 'block';
    genderEdit.style.display = 'none';
    gender.style.display = 'none';
});
genderCancel.addEventListener('click', function () {
    genderInput.style.display = 'none';
    genderSave.style.display = 'none';
    genderCancel.style.display = 'none';
    gender.style.color = 'gray';
    gender.style.display = 'block';
    genderEdit.style.display = 'block';
    console.log('操作取消');
});
genderSave.addEventListener('click', function(e) {
    // 获取选中的性别值
    e.preventDefault();
    const selectedGender = document.querySelector('input[name="gender"]:checked')?.value;

    if (!selectedGender) {
        showCustomAlert('请选择性别');
        return;
    }

    $.ajax({
        url: `http://localhost:8080/edit-person/updateGender`,
        method: 'POST',
            contentType: 'text/plain', // 改为纯文本格式
            data: selectedGender, // 直接发送字符串值，如 "男"
            dataType: 'json', // 期望后端返回JSON
            success: function(response) {
            if (response.success) {
                gender.textContent = selectedGender;
                gender.style.display = 'block';
                gender.style.color = 'gray';
                genderInput.style.display = 'none';
                genderSave.style.display = 'none';
                genderCancel.style.display = 'none';
                genderEdit.style.display = 'block';
                showCustomAlert('性别已更新为:' + selectedGender,3000);
                console.log('更新成功:', response);
            }
        },
        error: function (xhr, status, error) {
            console.error('更新性别失败:', error);
            genderInput.style.display = 'none';
            genderSave.style.display = 'none';
            genderCancel.style.display = 'none';
            gender.style.display = 'block';
            genderEdit.style.display = 'block';
            showCustomAlert('网络错误，请重试',3000);
        }
    });
});
//一句话介绍
const introEdit = document.getElementById('intro-edit');
const introInput = document.getElementById('intro-input');
const introSave = document.getElementById('intro-save');
const introCancel = document.getElementById('intro-cancel');
const title = document.querySelector('.title1');
const write1 = document.querySelector('.write1');
write1.addEventListener('click', function () {
    const currentshortBio = title.textContent.trim();
   introInput.value = currentshortBio === '未设置' || currentshortBio=== '未填写' ? '' :currentshortBio;
    introInput.style.display = 'block';
    introSave.style.display = 'block';
    introCancel.style.display = 'block';
    introEdit.style.display = 'none';
    title.style.color = 'gray';
});
introSave.addEventListener('click', function () {
    const shortBioValue = introInput.value;
    $.ajax({
        url: `http://localhost:8080/edit-person/updateShortBio`,
        type: 'POST',
        data: { shortBio: shortBioValue },
        success: function (response) {
            console.log('后端响应:', response);
            // 修改判断条件以匹配后端响应格式
            if (response.success) {
                title.textContent = shortBioValue;
                title.style.color = 'gray';
                title.style.fontWeight = 400;
                write1.textContent = '✏️修改';
            } else {
                showCustomAlert(response.message),3000;
            }
            introInput.style.display = 'none';
            introSave.style.display = 'none';
            introCancel.style.display = 'none';
            introEdit.style.display = 'block';
        },
        error: function (error) {
            console.log('请求出错:', error);
            introInput.style.display = 'none';
            introSave.style.display = 'none';
            introCancel.style.display = 'none';
            introEdit.style.display = 'block';
        }
    });
});

introCancel.addEventListener('click', function () {
    introInput.style.display = 'none';
    introSave.style.display = 'none';
    introCancel.style.display = 'none';
    introEdit.style.display = 'block';
    console.log('操作取消');
});
const locationEdit = document.getElementById('location-edit');
const locationInput = document.getElementById('location-input');
const locationSave = document.getElementById('location-save');
const locationCancel = document.getElementById('location-cancel');
const title2 = document.querySelector('.title2');
const write2 = document.querySelector('.write2');

write2.addEventListener('click', function () {
    locationInput.style.display = 'block';
    locationSave.style.display = 'block';
    locationCancel.style.display = 'block';
    locationEdit.style.display = 'none';
});

locationSave.addEventListener('click', function () {
    const selectedLocation = locationInput.value;
    $.ajax({
        url:  `http://localhost:8080/edit-person/updateLocation`,
        type: 'POST',
        data: { location: selectedLocation }, // 传递键值对参数（表单参数）
        success: function (response) {
            console.log('后端响应:', response);
            title2.textContent = selectedLocation;
            title2.style.color = 'gray';
            title2.style.fontWeight = 400;
            write2.textContent = '✏️修改';
            locationInput.style.display = 'none';
            locationSave.style.display = 'none';
            locationCancel.style.display = 'none';
            locationEdit.style.display = 'block';
        },
        error: function (error) {
            console.log('请求出错:', error);
        }
    });
});

locationCancel.addEventListener('click', function () {
    locationInput.style.display = 'none';
    locationSave.style.display = 'none';
    locationCancel.style.display = 'none';
    locationEdit.style.display = 'block';
});

const industryEdit = document.getElementById('industry-write');
const industryInput = document.getElementById('categorySelect');
const industrySave = document.getElementById('industry-save');
const industryCancel = document.getElementById('industry-cancel');
const title3 = document.querySelector('.title3');

industryEdit.addEventListener('click', function () {
    industryInput.style.display = 'block';
    industrySave.style.display = 'block';
    industryCancel.style.display = 'block';
    industryEdit.style.display = 'none';
});

industrySave.addEventListener('click', function () {
    const selectedIndustry = industryInput.value;
    $.ajax({
        url: `http://localhost:8080/edit-person/updateIndustry`,
        type: 'POST',
        data: {industry:selectedIndustry},
        success: function (response) {
            console.log('后端响应:', response);
            if (selectedIndustry.trim()!== "") {
                industryEdit.textContent = '✏️修改';
                title3.textContent = selectedIndustry;
                title3.style.color = 'gray';
            } else {
                industryEdit.textContent = '✏️填写';
                title3.textContent = '未填写';
                title3.style.color = 'gray';
            }
            industryInput.style.display = 'none';
            industrySave.style.display = 'none';
            industryCancel.style.display = 'none';
            industryEdit.style.display = 'block';
        },
        error: function (error) {
            console.log('请求出错:', error);
        }
    });
});

industryCancel.addEventListener('click', function () {
    industryInput.style.display = 'none';
    industrySave.style.display = 'none';
    industryCancel.style.display = 'none';
    industryEdit.style.display = 'block';
});
//个人简介
const personEdit = document.getElementById('person-edit');
const personInput = document.getElementById('person-input');
const personSave = document.getElementById('person-save');
const personCancel = document.getElementById('person-cancel');
const title4 = document.querySelector('.title4');
const write4 = document.querySelector('.write4');
write4.addEventListener('click', function () {
    const currentBio = title4.textContent.trim();
    personInput.value = currentBio === '未设置' || currentBio === '未填写' ? '' : currentBio;

    // 显示编辑控件
    personInput.style.display = 'block';
    personSave.style.display = 'block';
    personCancel.style.display = 'block';
    personEdit.style.display = 'none';

    // 自动聚焦到输入框
    personInput.focus();
});

personSave.addEventListener('click', function () {
    const bioValue = personInput.value;
    $.ajax({
        url: `http://localhost:8080/edit-person/updateBio`,
        type: 'POST',
        data: {bio:bioValue},
        success: function (response) {
            console.log('后端响应:', response);
            if (response.success) {
                if (bioValue.trim() === '') {
                    write4.textContent = '✏️填写';
                    if (title4) {
                        title4.textContent = '未填写';
                        title4.style.color = 'gray';
                    }
                } else {
                    write4.textContent = '✏️修改';
                    title4.textContent = bioValue;
                    title4.style.fontWeight = 400;
                    title4.style.color = 'gary';
                }
            } else {
                showCustomAlert(response.result,3000);
            }
            personInput.style.display = 'none';
            personSave.style.display = 'none';
            personCancel.style.display = 'none';
            personEdit.style.display = 'block';
        },
        error: function (error) {
            console.log('请求出错:', error);
        }
    });
});

personCancel.addEventListener('click', function () {
    personInput.style.display = 'none';
    personSave.style.display = 'none';
    personCancel.style.display = 'none';
    personEdit.style.display = 'block';
});

const usernameSection = document.getElementById('username-form');
const username = document.querySelector('.edit-username');
const usernameInput = document.getElementById('username');
const errorMessage = document.querySelector('.error-message');
const edit = document.querySelector('.edit');
const usernameSave = document.getElementById('username-save');
const usernamecancel = document.getElementById('username-cancel');
// 显示修改用户名的区域
edit.addEventListener('click',function(){
    usernameSection.style.display = 'block';
    username.style.display = 'none';
    usernameInput.value = document.querySelector('.realname').textContent;
});

// 隐藏修改用户名的区域
usernamecancel.addEventListener('click',function() {
    usernameSection.style.display = 'none';
    username.style.display = 'block';
});

// 保存用户名
usernameSave.addEventListener('click',function(e){
    e.preventDefault();
    const usernameValue = usernameInput.value;
    $.ajax({
        url: `http://localhost:8080/edit-person/updateUsername`,
        type: 'POST',
        data: { username: usernameValue },
        success: function (response) {
            errorMessage.textContent = response.result;
            if (response.success) {
                document.querySelector('.realname').textContent = usernameValue;
                usernameSection.style.display = 'none';
                username.style.display = 'block';
            }
        },
        error: function (error) {
            errorMessage.textContent = '保存失败，请重试';
            usernameSection.style.display = 'none';
            username.style.display = 'block';
        }
    });
});
//最新数据

//改头像;
// 获取相关元素
const img = document.getElementById('img');
const photoEdit = document.getElementById('photo-edit');
const fileInput = document.querySelector('.file');
const imgElement = document.getElementById('uimg');

// 为图片和“修改我的头像”区域绑定点击事件
img.addEventListener('click', function () {
    fileInput.click();
});

photoEdit.addEventListener('click', function () {
    fileInput.click();
});

// 选择图片并上传
fileInput.addEventListener('change', function (e) {
    const file = this.files[0];
    if (file) {
        // 预览图片
        const imgurl = window.URL || window.webkitURL;
        const newImg = new Image();
        newImg.onload = function () {
            imgElement.src = this.src;
            imgurl.revokeObjectURL(this.src);
        };
        newImg.src = imgurl.createObjectURL(file);
        console.log(13);
        // 上传图片到后端
        uploadAvatar(file);
        console.log(14);
    }
});
// 执行上传的函数
function uploadAvatar(file) {
    const formData = new FormData();
    formData.append('file', file);
    console.log(31);
    $.ajax({
        url: '/userHomepage/updateAvatar',
        type: 'POST',
        data: formData,
        processData: false, // 重要：不处理数据
        contentType: false, // 重要：不设置内容类型
        success: function (response) {
            showCustomAlert('头像上传成功',3000);
            // 可以在这里更新页面上的头像显示
        },
        error: function (error) {
            console.error('上传失败:', error);
            showCustomAlert('上传失败，请重试',3000);
        }
    });
}

//背景图
// 获取相关元
// 绑定点击事件
function uploadBackground(file) {
    const formData = new FormData();
    formData.append('file', file);

    $.ajax({
        url: `/userHomepage/updateBackground`, // 与后端接口路径一致
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function (response) {
            if (response.success) {
                // 关键：动态更新 img.src（无需依赖 Thymeleaf）
                const imgElement = document.getElementById('uimgs');
                imgElement.src = response.url; // 直接使用后端返回的 URL

                // 可选：缓存路径到 localStorage（用于刷新后恢复）
                localStorage.setItem('backgroundUrl', response.url);

                showCustomAlert('背景图更新成功',3000);
            } else {
                showCustomAlert('上传失败：' + response.message,3000);
            }
        },
        error: function (xhr, status, error) {
            console.error('上传失败:', error);
            showCustomAlert('网络错误，请重试',3000);
        }
    });
}

// 绑定文件选择事件（点击上传区域触发）
document.querySelector('.photo').addEventListener('click', function () {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.onchange = function (e) {
        const file = e.target.files[0];
        if (file) {
            uploadBackground(file);
        }
    };
    fileInput.click();
});

// 页面加载时：从 localStorage 恢复路径（可选）
window.addEventListener('load', function () {
    const savedUrl = localStorage.getItem('backgroundUrl');
    if (savedUrl) {
        document.getElementById('uimgs').src = savedUrl;
    }
});